#include "QuickJSTest.h"

#include <gtest/gtest.h>

#include "QuickJS/cutils.h"
#include "QuickJS/quickjs-libc.h"

TEST_F(QjsTest, ByteCode) {
  testing::internal::CaptureStdout();
  const uint32_t qjsc_sayhello_size = 81;

  const uint8_t qjsc_sayhello[81] = {
      0x02, 0x04, 0x0e, 0x63, 0x6f, 0x6e, 0x73, 0x6f, 0x6c, 0x65, 0x06, 0x6c, 0x6f, 0x67, 0x16, 0x68, 0x65,
      0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x16, 0x73, 0x61, 0x79, 0x68, 0x65, 0x6c, 0x6c,
      0x6f, 0x2e, 0x6a, 0x73, 0x0e, 0x00, 0x06, 0x00, 0xa0, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x14,
      0x01, 0xa2, 0x01, 0x00, 0x00, 0x00, 0x38, 0xe1, 0x00, 0x00, 0x00, 0x42, 0xe2, 0x00, 0x00, 0x00, 0x04,
      0xe3, 0x00, 0x00, 0x00, 0x24, 0x01, 0x00, 0xcd, 0x28, 0xc8, 0x03, 0x01, 0x00,
  };

  JSValue obj = JS_ReadObject(context, qjsc_sayhello, 81, JS_READ_OBJ_BYTECODE);
  JSValue val = JS_EvalFunction(context, obj);
  JS_FreeValue(context, val);
  std::string output = testing::internal::GetCapturedStdout();
  EXPECT_EQ(output, "hello world\n");
}

TEST_F(QjsTest, JsSource) {
  testing::internal::CaptureStdout();
  auto result = JS_Eval(context, defaultScript, sizeof(defaultScript) - 1, "<input>", JS_EVAL_TYPE_MODULE);
  JS_FreeValue(context, result);
  std::string output = testing::internal::GetCapturedStdout();
  EXPECT_EQ(output, "hello qjs\n");
}
